
const config = require('./config');
const mysql = require('mysql');

var connection = mysql.createConnection(config.db);

var isConnect = false;

module.exports = {
	connect: function() {
		if (!isConnect) {
			connection.connect(function(error) {
				if (error == null) {
					isConnect = true;
					console.log('db connect success');
				}
			});
		}
		return this;
	},
	query: function(sql, values, fn) {
		this.connect();
		var me = this;
		connection.query(sql, values || [], function(error, results, fields) {
			if (typeof fn === 'function')
				fn.call(me, error, results, fields);
		});
		return this;
	},
	close: function() {
		if (connection && isConnect)
			connection.close();
		return this;
	},
	row: function(rows, index) {
		if (typeof rows === 'undefined' || typeof rows[index] === 'undefined')
			return false;
		return rows[index];
	}
};

